package com.company.project.web;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.IoUtil;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.company.project.core.Result;
import com.company.project.core.ResultGenerator;
import com.company.project.model.TtbPetshopMember;
import com.company.project.model.TtbPetshopMemberCardConsume;
import com.company.project.model.TtbPetshopMemberCardConsumeRecord;
import com.company.project.service.TtbPetshopMemberCardConsumeRecordService;
import com.company.project.service.TtbPetshopMemberCardConsumeService;
import com.company.project.service.TtbPetshopMemberService;
import com.company.project.vo.Member;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Date;
import java.util.Optional;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import org.apache.poi.ss.usermodel.Sheet;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.List;
import tk.mybatis.mapper.entity.Condition;
import tk.mybatis.mapper.entity.Example;
import tk.mybatis.mapper.entity.Example.Criteria;

/**
* Created by CodeGenerator on 2020/06/05.
*/
@RestController
@RequestMapping("/ttb/petshop/member")
public class TtbPetshopMemberController {
    @Resource
    private TtbPetshopMemberService ttbPetshopMemberService;

    @Resource
    private TtbPetshopMemberCardConsumeService ttbPetshopMemberCardConsumeService;

    @Resource
    private TtbPetshopMemberCardConsumeRecordService ttbPetshopMemberCardConsumeRecordService;

    @PostMapping("/add")
    public Result add(TtbPetshopMember ttbPetshopMember) {
        ttbPetshopMemberService.save(ttbPetshopMember);
        return ResultGenerator.genSuccessResult();
    }

    @PostMapping("/delete")
    public Result delete(@RequestParam Integer id) {
        ttbPetshopMemberService.deleteById(id);
        return ResultGenerator.genSuccessResult();
    }

    @PostMapping("/update")
    public Result update(TtbPetshopMember ttbPetshopMember) {
        ttbPetshopMemberService.update(ttbPetshopMember);
        return ResultGenerator.genSuccessResult();
    }

    @PostMapping("/detail")
    public Result detail(@RequestParam Integer id) {
        TtbPetshopMember ttbPetshopMember = ttbPetshopMemberService.findById(id);
        return ResultGenerator.genSuccessResult(ttbPetshopMember);
    }

    @GetMapping("/list")
    public Result list(@RequestParam(defaultValue = "0") Integer page, @RequestParam(defaultValue = "0") Integer size) {
        PageHelper.startPage(page, size);
        List<TtbPetshopMember> list = ttbPetshopMemberService.findAll();
        PageInfo pageInfo = new PageInfo(list);
        return ResultGenerator.genSuccessResult(pageInfo);
    }

    @GetMapping("/export")
    @ResponseBody
    public void export(HttpServletResponse response, String shopId) {

        Condition condition = new Condition(TtbPetshopMember.class);
        Example.Criteria criteria = condition.createCriteria();
        criteria.andEqualTo("petshopId", shopId);
        // criteria.andEqualTo("isDelete", 0);
        List<TtbPetshopMember> ttbPetshopMembers = ttbPetshopMemberService.findByCondition(condition);

        List<Member> members = new ArrayList<>();
        for (TtbPetshopMember ttbPetshopMember : ttbPetshopMembers) {
            String memberName = ttbPetshopMember.getMemberName();
            String memberMobile = ttbPetshopMember.getMemberMobile();
            Long id = ttbPetshopMember.getId();
            String cardBalance = this.getCardBalance(id);
            String rechargeConsume = this.getRechargeConsume(id);
            Boolean isDelete = ttbPetshopMember.getIsDelete();
            Date modifyDate = ttbPetshopMember.getModifyDate();

            Member member = Member.builder()
                .name(memberName)
                .phone(memberMobile)
                .cardBalance(cardBalance)
                .rechargeConsume(rechargeConsume)
                //.isDelete(isDelete ? "是" : "")
                //.deleteTime(isDelete ? DateUtil.formatDateTime(modifyDate) : "")
                .build();
            members.add(member);
        }

        ExcelWriter writer = ExcelUtil.getWriter();
        writer.addHeaderAlias("name", "姓名");
        writer.addHeaderAlias("phone", "手机号");
        //writer.addHeaderAlias("isDelete", "是否删除");
        //writer.addHeaderAlias("deleteTime", "删除时间");
        writer.addHeaderAlias("cardBalance", "卡内余额");
        writer.addHeaderAlias("rechargeConsume", "充值及消费记录");

        writer.write(members);

        Sheet sheet = writer.getSheet();
        sheet.setDefaultColumnWidth(20);
        sheet.setColumnWidth(3, 10000);
//        sheet.setColumnWidth(5, 10000);

        response.setContentType("application/vnd.ms-excel;charset=utf-8");

        try {
            String fileName = URLEncoder.encode("会员相关信息","utf-8");
            response.setHeader("Content-Disposition", "attachment;filename=" + fileName + ".xls");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        ServletOutputStream out = null;

        try {
            out = response.getOutputStream();
            writer.flush(out);

        } catch (IOException e) {

            e.printStackTrace();

        } finally {
            writer.close();
        }

        IoUtil.close(out);
    }

    /**
     * 获得卡余额
     * @return
     */
    public String getCardBalance(Long memberId) {
        System.out.println("memberId " + memberId);
        String cardBalanceStr = "";

        Condition condition = new Condition(TtbPetshopMemberCardConsume.class);
        condition.orderBy("createDate").desc();
        Criteria criteria = condition.createCriteria();
        criteria.andCondition("member_id=" + memberId);

        List<TtbPetshopMemberCardConsume> ttbPetshopMemberCardConsumes = ttbPetshopMemberCardConsumeService.findByCondition(condition);
        if (CollUtil.isNotEmpty(ttbPetshopMemberCardConsumes)) {
            TtbPetshopMemberCardConsume ttbPetshopMemberCardConsume = ttbPetshopMemberCardConsumes.get(0);
            if (ttbPetshopMemberCardConsume != null) {
                BigDecimal cardBalance = ttbPetshopMemberCardConsume.getCardBalance();
                cardBalanceStr = NumberUtil.roundStr(cardBalance.toString(), 2);
            }
        } else {
            cardBalanceStr = "无充值卡";
        }

        return cardBalanceStr;
    }

    /**
     * 获得消费记录
     * @return
     */
    public String getRechargeConsume(Long memberId) {
        StringBuilder descSb = new StringBuilder();
        Condition condition = new Condition(TtbPetshopMemberCardConsumeRecord.class);
        condition.orderBy("createDate").asc();
        Criteria criteria = condition.createCriteria();
        criteria.andCondition("member_id=" + memberId);
        List<TtbPetshopMemberCardConsumeRecord> ttbPetshopMemberCardConsumeRecords = ttbPetshopMemberCardConsumeRecordService
            .findByCondition(condition);
        for (TtbPetshopMemberCardConsumeRecord ttbPetshopMemberCardConsumeRecord : ttbPetshopMemberCardConsumeRecords) {
            StringBuilder sb = new StringBuilder();
            Date createDate = ttbPetshopMemberCardConsumeRecord.getCreateDate();
            BigDecimal changeBalance = ttbPetshopMemberCardConsumeRecord.getChangeBalance();
            BigDecimal changeLaterBalance = ttbPetshopMemberCardConsumeRecord.getChangeLaterBalance();
            String changeType = ttbPetshopMemberCardConsumeRecord.getChangeType();
            String rechargeConsumeDesc = changeType.equals("消费") ? "消费" : "充值";
            String createDateFormat = DateUtil.formatDate(createDate);
            sb.append(createDateFormat).append(rechargeConsumeDesc+ ":" + NumberUtil.roundStr(changeBalance.toString(), 2))
                .append("剩余:" + NumberUtil.roundStr(changeLaterBalance.toString(), 2)).append("\n");
            descSb.append(sb.toString());
        }
        return descSb.toString();
    }

}
